"""
    Utility classes for logging users actions.
"""

from datetime import datetime
from sqlobject.col import UnicodeCol, ForeignKey, DateTimeCol, IntCol
from sqlobject.joins import MultipleJoin

from mnemoply.model.model_object import ModelObject

from mnemoply.model.hub import __connection__

class AuditObjectClass(ModelObject):
    model_title = "Audit!ObjectClass"

    name = UnicodeCol(length=100, notNull=True, alternateID=True, title=_("Name"))
    title = property(lambda self: self.name)

class AuditActionUrl(ModelObject):
    model_title = "Audit!ActionUrl"

    url = UnicodeCol(length=200, notNull=True, alternateID=True, title=_("Url"))
    title = property(lambda self: self.url)

class AuditChange(ModelObject):
    model_title = "Audit!Change"

    transaction = ForeignKey('AuditTransactionRecord', notNull=True, title=_("Transaction"))

    kind = UnicodeCol(length=1, varchar=False, notNull=True, title=_("Kind"))
    objectTitle = UnicodeCol(length=200, notNull=True, title=_("ObjTitle"))
    objectClass = ForeignKey('AuditObjectClass', notNull=True, title=_("ObjClass"))
    objectId = IntCol(notNull=True, title="ObjId")

    details = UnicodeCol(default='', notNull=True, title=_("ObjTitle"))

    def getTitle(self):
        return "%s: %s %s:%d %s" % (self.transaction.title,
            self.kind,
            self.objectClass.title, self.objectId,
            self.objectTitle,
        )

    title = property(getTitle)

class AuditTransactionRecord(ModelObject):
    model_title = "Audit!Transaction"

    timestamp = DateTimeCol(notNull=True, default=datetime.now, title=_("Timestamp"))
    user = ForeignKey('AuthUser', notNull=True, title=_("User"))
    actionUrl = ForeignKey('AuditActionUrl', notNull=True, title=_("Action url"))

    changes = MultipleJoin('AuditChange', joinColumn="transaction_id")

    def getTitle(self):
        return "%s %s %s" % (str(self.timestamp),
            self.user.user_name, self.actionUrl)

    title = property(getTitle)
